<template>
    <div id="Application">
      <!-- 游戏区域 -->
      <div class="container">
        <!-- 底部挡板 -->
        <div class="board" :style="{ left: boardX + 'px' }"></div>
        <!-- 弹球 -->
        <div class="ball" :style="{ left: ballX + 'px', top: ballY + 'px' }"></div>
        <!-- 游戏结束提示 -->
        <h1 v-if="fail" style="text-align: center;">游戏失败</h1>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  
  // 控制挡板位置
  const boardX = ref(0);
  // 控制弹球位置
  const ballX = ref(0);
  const ballY = ref(0);
  // 控制弹球移动速度
  const rateX = ref(0.1);
  const rateY = ref(0.1);
  // 控制结束游戏提示的展示
  const fail = ref(false);
  
  // 组件挂载时执行的函数
  onMounted(() => {
    // 添加键盘事件
    enterKeyup();
    // 随机弹球的运动速度和方向
    rateX.value = Math.random() * 0.5 + 0.1;
    rateY.value = Math.random() * 0.5 + 0.1;
  
    // 开启计数器，控制弹球移动
    const timer = setInterval(() => {
      // 到达右侧边缘进行反弹
      if (ballX.value + rateX.value >= 440 - 30) {
        rateX.value *= -1;
      }
      // 到达左侧边缘进行反弹
      if (ballX.value + rateX.value <= 0) {
        rateX.value *= -1;
      }
      // 到达上侧边缘进行反弹
      if (ballY.value + rateY.value <= 0) {
        rateY.value *= -1;
      }
  
      ballX.value += rateX.value;
      ballY.value += rateY.value;
  
      // 失败判定
      if (ballY.value >= 440 - 30 - 10) {
        // 挡板接住了弹球，进行反弹
        if (boardX.value <= ballX.value + 30 && boardX.value + 80 >= ballX.value) {
          rateY.value *= -1;
        } else {
          // 没有接住弹球，游戏结束
          clearInterval(timer);
          fail.value = true;
        }
      }
    }, 2);
  });
  
  // 控制挡板移动
  const keydown = (event) => {
    if (event.key === "ArrowLeft") {
      if (boardX.value > 10) {
        boardX.value -= 20;
      }
    } else if (event.key === "ArrowRight") {
      if (boardX.value < 440 - 80) {
        boardX.value += 20;
      }
    }
  };
  
  const enterKeyup = () => {
    document.addEventListener("keydown", keydown);
  };
  </script>
  
  <style>
  body {
    margin: 0;
    padding: 0;
  }
  
  .container {
    position: relative;
    margin: 0 auto;
    width: 440px;
    height: 440px;
    background-color: blanchedalmond;
  }
  
  .ball {
    position: absolute;
    width: 30px;
    height: 30px;
    left: 0px;
    top: 0px;
    background-color: orange;
    border-radius: 30px;
  }
  
  .board {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 10px;
    width: 80px;
    border-radius: 5px;
    background-color: red;
  }
  </style>